<template>
  <div class="payment-password-page">
    <Header :scroll="scroll" />

    <!-- 支付密码设置内容区域 -->
    <div class="payment-password-content">
      <div class="container">
        <div class="payment-password-wrapper">
          <!-- 左侧品牌信息 -->
          <div class="brand-section">
            <div class="brand-content">
              <img src="@/assets/logo-full.png" alt="六堡茶" class="brand-logo" />
              <h2 class="brand-title">{{ hasPaymentPassword ? '修改支付密码' : '设置支付密码' }}</h2>
              <p class="brand-desc">{{ hasPaymentPassword ? '为了您的资金安全，请定期更换支付密码' : '设置支付密码，保护您的资金安全' }}</p>
              <div class="steps-indicator">
                <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
                  <div class="step-number">1</div>
                  <span class="step-text">{{ hasPaymentPassword ? '验证当前密码' : '验证身份' }}</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
                  <div class="step-number">2</div>
                  <span class="step-text">设置新密码</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
                  <div class="step-number">3</div>
                  <span class="step-text">完成设置</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-section">
            <div class="form-container">
              <!-- 步骤1：验证身份或当前支付密码 -->
              <div v-if="currentStep === 1" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">{{ hasPaymentPassword ? '验证当前支付密码' : '验证身份' }}</h3>
                  <p class="form-subtitle">{{ hasPaymentPassword ? '请输入您当前的6位支付密码' : '请输入您的登录密码进行身份验证' }}</p>
                </div>

                <el-form ref="verifyFormRef" :model="verifyForm" :rules="verifyRules" class="payment-form">
                  <el-form-item v-if="hasPaymentPassword" prop="currentPaymentPassword">
                    <div class="payment-input-container">
                      <div class="payment-input-wrapper">
                        <input
                          v-for="(digit, index) in currentPaymentPasswordDigits"
                          :key="index"
                          :ref="(el) => setCurrentPasswordInputRef(el, index)"
                          v-model="currentPaymentPasswordDigits[index]"
                          type="password"
                          maxlength="1"
                          class="payment-digit-input"
                          @input="handleCurrentPasswordInput(index, $event)"
                          @keydown="handleCurrentPasswordKeydown(index, $event)" />
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item v-else prop="loginPassword">
                    <el-input
                      v-model="verifyForm.loginPassword"
                      type="password"
                      placeholder="请输入登录密码"
                      size="large"
                      prefix-icon="Lock"
                      show-password
                      clearable />
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleVerifySubmit">
                      {{ loading ? '验证中...' : '下一步' }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤2：设置新支付密码 -->
              <div v-if="currentStep === 2" class="step-content">
                <div class="form-header">
                  <h3 class="form-title">设置支付密码</h3>
                  <p class="form-subtitle">请设置6位数字支付密码</p>
                </div>

                <el-form ref="newPasswordFormRef" :model="newPasswordForm" :rules="newPasswordRules" class="payment-form">
                  <el-form-item prop="newPaymentPassword">
                    <div class="payment-input-container">
                      <label class="input-label">新支付密码</label>
                      <div class="payment-input-wrapper">
                        <input
                          v-for="(digit, index) in newPaymentPasswordDigits"
                          :key="index"
                          :ref="(el) => setNewPasswordInputRef(el, index)"
                          v-model="newPaymentPasswordDigits[index]"
                          type="password"
                          maxlength="1"
                          class="payment-digit-input"
                          @input="handleNewPasswordInput(index, $event)"
                          @keydown="handleNewPasswordKeydown(index, $event)" />
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item prop="confirmPaymentPassword">
                    <div class="payment-input-container">
                      <label class="input-label">确认支付密码</label>
                      <div class="payment-input-wrapper">
                        <input
                          v-for="(digit, index) in confirmPaymentPasswordDigits"
                          :key="index"
                          :ref="(el) => setConfirmPasswordInputRef(el, index)"
                          v-model="confirmPaymentPasswordDigits[index]"
                          type="password"
                          maxlength="1"
                          class="payment-digit-input"
                          @input="handleConfirmPasswordInput(index, $event)"
                          @keydown="handleConfirmPasswordKeydown(index, $event)" />
                      </div>
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <div class="button-group">
                      <el-button size="large" @click="goBack">上一步</el-button>
                      <el-button type="primary" size="large" class="submit-btn" :loading="loading" @click="handleNewPasswordSubmit">
                        {{ loading ? '设置中...' : '确认设置' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 步骤3：完成提示 -->
              <div v-if="currentStep === 3" class="step-content success-content">
                <div class="success-icon">✓</div>
                <h3 class="success-title">{{ hasPaymentPassword ? '支付密码修改成功！' : '支付密码设置成功！' }}</h3>
                <p class="success-desc">
                  {{ hasPaymentPassword ? '您的支付密码已成功修改，请妥善保管' : '您已成功设置支付密码，可以安全地进行支付操作' }}
                </p>
                <el-button type="primary" size="large" class="submit-btn" @click="goToProfile"> 返回个人中心 </el-button>
              </div>

              <!-- 返回链接 -->
              <div v-if="currentStep < 3" class="form-footer">
                <span class="back-text">不想设置了？</span>
                <router-link to="/profile" class="back-link">返回个人中心</router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const userStore = useUserStore()
  const scroll = ref(false)
  const verifyFormRef = ref()
  const newPasswordFormRef = ref()
  const loading = ref(false)
  const currentStep = ref(1)

  const userInfo = computed(() => userStore.userInfo)

  // 模拟用户是否已设置支付密码（实际应从后端获取）
  const hasPaymentPassword = ref(false)

  // 输入框引用
  const currentPasswordInputRefs = ref([])
  const newPasswordInputRefs = ref([])
  const confirmPasswordInputRefs = ref([])

  // 支付密码数字数组
  const currentPaymentPasswordDigits = ref(['', '', '', '', '', ''])
  const newPaymentPasswordDigits = ref(['', '', '', '', '', ''])
  const confirmPaymentPasswordDigits = ref(['', '', '', '', '', ''])

  // 监听滚动
  onMounted(() => {
    window.addEventListener('scroll', () => {
      scroll.value = window.scrollY > 0
    })

    // 检查用户是否已设置支付密码（实际应调用API）
    checkPaymentPasswordStatus()
  })

  // 检查支付密码状态
  const checkPaymentPasswordStatus = async () => {
    try {
      // 这里应该调用实际的API检查用户是否已设置支付密码
      hasPaymentPassword.value = userInfo.value.has_password_secure === '已设置'
    } catch (error) {
      console.error('检查支付密码状态失败:', error)
    }
  }

  // 表单数据
  const verifyForm = reactive({
    currentPaymentPassword: '',
    loginPassword: '',
  })

  const newPasswordForm = reactive({
    newPaymentPassword: '',
    confirmPaymentPassword: '',
  })

  // 计算属性：将数字数组转换为字符串
  const currentPaymentPasswordString = computed(() => {
    return currentPaymentPasswordDigits.value.join('')
  })

  const newPaymentPasswordString = computed(() => {
    return newPaymentPasswordDigits.value.join('')
  })

  const confirmPaymentPasswordString = computed(() => {
    return confirmPaymentPasswordDigits.value.join('')
  })

  // 自定义验证函数
  const validateCurrentPaymentPassword = (rule, value, callback) => {
    const password = currentPaymentPasswordString.value
    if (password.length !== 6) {
      callback(new Error('请输入6位支付密码'))
    } else if (!/^\d{6}$/.test(password)) {
      callback(new Error('支付密码只能是数字'))
    } else {
      callback()
    }
  }

  const validateLoginPassword = (rule, value, callback) => {
    if (!value) {
      callback(new Error('请输入登录密码'))
    } else if (value.length < 6) {
      callback(new Error('密码长度不能少于6位'))
    } else {
      callback()
    }
  }

  const validateNewPaymentPassword = (rule, value, callback) => {
    const password = newPaymentPasswordString.value
    if (password.length !== 6) {
      callback(new Error('请输入6位支付密码'))
    } else if (!/^\d{6}$/.test(password)) {
      callback(new Error('支付密码只能是数字'))
    } else {
      callback()
    }
  }

  const validateConfirmPaymentPassword = (rule, value, callback) => {
    const newPassword = newPaymentPasswordString.value
    const confirmPassword = confirmPaymentPasswordString.value
    if (confirmPassword.length !== 6) {
      callback(new Error('请输入6位支付密码'))
    } else if (confirmPassword !== newPassword) {
      callback(new Error('两次输入的支付密码不一致'))
    } else {
      callback()
    }
  }

  // 表单验证规则
  const verifyRules = computed(() => {
    if (hasPaymentPassword.value) {
      return {
        currentPaymentPassword: [{ validator: validateCurrentPaymentPassword, trigger: 'blur' }],
      }
    } else {
      return {
        loginPassword: [{ validator: validateLoginPassword, trigger: 'blur' }],
      }
    }
  })

  const newPasswordRules = {
    newPaymentPassword: [{ validator: validateNewPaymentPassword, trigger: 'blur' }],
    confirmPaymentPassword: [{ validator: validateConfirmPaymentPassword, trigger: 'blur' }],
  }

  // 设置输入框引用
  const setCurrentPasswordInputRef = (el, index) => {
    if (el) {
      currentPasswordInputRefs.value[index] = el
    }
  }

  const setNewPasswordInputRef = (el, index) => {
    if (el) {
      newPasswordInputRefs.value[index] = el
    }
  }

  const setConfirmPasswordInputRef = (el, index) => {
    if (el) {
      confirmPasswordInputRefs.value[index] = el
    }
  }

  // 处理当前支付密码输入
  const handleCurrentPasswordInput = (index, event) => {
    const value = event.target.value
    if (!/^\d$/.test(value) && value !== '') {
      currentPaymentPasswordDigits.value[index] = ''
      return
    }

    currentPaymentPasswordDigits.value[index] = value
    verifyForm.currentPaymentPassword = currentPaymentPasswordString.value

    if (value && index < 5) {
      currentPasswordInputRefs.value[index + 1]?.focus()
    }
  }

  const handleCurrentPasswordKeydown = (index, event) => {
    if (event.key === 'Backspace' && !currentPaymentPasswordDigits.value[index] && index > 0) {
      currentPasswordInputRefs.value[index - 1]?.focus()
    }
  }

  // 处理新支付密码输入
  const handleNewPasswordInput = (index, event) => {
    const value = event.target.value
    if (!/^\d$/.test(value) && value !== '') {
      newPaymentPasswordDigits.value[index] = ''
      return
    }

    newPaymentPasswordDigits.value[index] = value
    newPasswordForm.newPaymentPassword = newPaymentPasswordString.value

    if (value && index < 5) {
      newPasswordInputRefs.value[index + 1]?.focus()
    }
  }

  const handleNewPasswordKeydown = (index, event) => {
    if (event.key === 'Backspace' && !newPaymentPasswordDigits.value[index] && index > 0) {
      newPasswordInputRefs.value[index - 1]?.focus()
    }
  }

  // 处理确认支付密码输入
  const handleConfirmPasswordInput = (index, event) => {
    const value = event.target.value
    if (!/^\d$/.test(value) && value !== '') {
      confirmPaymentPasswordDigits.value[index] = ''
      return
    }

    confirmPaymentPasswordDigits.value[index] = value
    newPasswordForm.confirmPaymentPassword = confirmPaymentPasswordString.value

    if (value && index < 5) {
      confirmPasswordInputRefs.value[index + 1]?.focus()
    }
  }

  const handleConfirmPasswordKeydown = (index, event) => {
    if (event.key === 'Backspace' && !confirmPaymentPasswordDigits.value[index] && index > 0) {
      confirmPasswordInputRefs.value[index - 1]?.focus()
    }
  }

  // 处理验证提交
  const handleVerifySubmit = async () => {
    if (!verifyFormRef.value) return

    try {
      const valid = await verifyFormRef.value.validate()
      if (!valid) return

      loading.value = true

      if (hasPaymentPassword.value) {
        // 验证当前支付密码
        console.log('验证当前支付密码:', currentPaymentPasswordString.value)
        apiUser.VerifyPaymentPsw({ old_password_secure: currentPaymentPasswordString.value }).then((res) => {
          ElMessage.success('验证成功')
          // 进入下一步
          currentStep.value = 2
        })
      } else {
        // 验证登录密码
        console.log('验证登录密码:', verifyForm.loginPassword)
        apiUser.VerifyLoginPsw({ old_password_login: verifyForm.loginPassword }).then((res) => {
          ElMessage.success('验证成功')
          // 进入下一步
          currentStep.value = 2
        })
      }
    } catch (error) {
      console.error('验证失败:', error)
      ElMessage.error(hasPaymentPassword.value ? '当前支付密码错误' : '登录密码错误')
    } finally {
      loading.value = false
    }
  }

  // 处理新密码设置
  const handleNewPasswordSubmit = async () => {
    if (!newPasswordFormRef.value) return

    try {
      const valid = await newPasswordFormRef.value.validate()
      if (!valid) return

      // 检查新密码是否与当前密码相同（如果是修改密码）
      if (hasPaymentPassword.value && newPaymentPasswordString.value === currentPaymentPasswordString.value) {
        ElMessage.warning('新支付密码不能与当前密码相同')
        return
      }

      loading.value = true

      // 模拟API调用设置支付密码
      const saveData = {
        old_password_login: verifyForm.loginPassword,
        old_password_secure: currentPaymentPasswordString.value,
        new_password_secure: newPaymentPasswordString.value,
      }
      apiUser.UpdatePaymentPsw(saveData).then((res) => {
        ElMessage.success(hasPaymentPassword.value ? '支付密码修改成功！' : '支付密码设置成功！')
        // 进入完成步骤
        currentStep.value = 3
        userInfo.value.has_password_secure = '已设置'
        userStore.updateUserInfo(userInfo.value)
      })
    } catch (error) {
      console.error('设置支付密码失败:', error)
      ElMessage.error('操作失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 返回上一步
  const goBack = () => {
    if (currentStep.value > 1) {
      currentStep.value--
    }
  }

  // 返回个人中心
  const goToProfile = () => {
    router.push('/profile')
  }
</script>

<style scoped>
  .payment-password-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .payment-password-content {
    padding: 60px 0;
    min-height: calc(100vh - 200px);
    display: flex;
    align-items: center;
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .payment-password-wrapper {
    display: flex;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    min-height: 600px;
  }

  /* 左侧品牌区域 */
  .brand-section {
    flex: 1;
    background: linear-gradient(135deg, #1c705e 0%, #2d8a6e 100%);
    color: white;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .brand-content {
    text-align: center;
    max-width: 400px;
  }

  .brand-logo {
    width: 120px;
    height: auto;
    margin-bottom: 30px;
  }

  .brand-title {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 16px;
  }

  .brand-desc {
    font-size: 16px;
    margin-bottom: 40px;
    opacity: 0.9;
    line-height: 1.6;
  }

  /* 步骤指示器 */
  .steps-indicator {
    display: flex;
    flex-direction: column;
    gap: 30px;
  }

  .step {
    display: flex;
    align-items: center;
    gap: 15px;
    opacity: 0.6;
    transition: all 0.3s ease;
  }

  .step.active {
    opacity: 1;
  }

  .step.completed {
    opacity: 0.8;
  }

  .step-number {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: 600;
  }

  .step.active .step-number {
    background: white;
    color: #1c705e;
  }

  .step.completed .step-number {
    background: #4ade80;
    color: white;
  }

  .step-text {
    font-size: 14px;
    font-weight: 500;
  }

  /* 右侧表单区域 */
  .form-section {
    flex: 1;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
  }

  .step-content {
    min-height: 300px;
  }

  .form-header {
    text-align: center;
    margin-bottom: 40px;
  }

  .form-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .form-subtitle {
    color: #666;
    font-size: 14px;
  }

  .payment-form {
    margin-bottom: 30px;
  }

  .payment-form .el-form-item {
    margin-bottom: 24px;
  }

  /* 支付密码输入框样式 */
  .payment-input-container {
    width: 100%;
  }

  .input-label {
    display: block;
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .payment-input-wrapper {
    display: flex;
    gap: 12px;
    justify-content: center;
  }

  .payment-digit-input {
    width: 45px;
    height: 45px;
    border: 2px solid #dcdfe6;
    border-radius: 8px;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    outline: none;
    transition: all 0.3s ease;
  }

  .payment-digit-input:focus {
    border-color: #1c705e;
    box-shadow: 0 0 0 2px rgba(28, 112, 94, 0.2);
  }

  .payment-digit-input::-webkit-outer-spin-button,
  .payment-digit-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  .payment-digit-input[type='number'] {
    -moz-appearance: textfield;
  }

  .button-group {
    display: flex;
    gap: 12px;
  }

  .button-group .el-button {
    flex: 1;
    height: 48px;
    font-size: 16px;
  }

  .submit-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    background: #1c705e;
    border-color: #1c705e;
  }

  /* 在button-group中的submit-btn不使用width: 100% */
  .button-group .submit-btn {
    width: auto;
  }

  .submit-btn:hover {
    background: #2d8a6e;
    border-color: #2d8a6e;
  }

  /* 成功页面 */
  .success-content {
    text-align: center;
    padding: 40px 0;
  }

  .success-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: #4ade80;
    color: white;
    font-size: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 30px;
  }

  .success-title {
    font-size: 24px;
    color: #333;
    margin-bottom: 16px;
  }

  .success-desc {
    color: #666;
    margin-bottom: 40px;
    line-height: 1.6;
  }

  .form-footer {
    text-align: center;
    font-size: 14px;
    color: #666;
  }

  .back-link {
    color: #1c705e;
    text-decoration: none;
    font-weight: 600;
    margin-left: 8px;
  }

  .back-link:hover {
    text-decoration: underline;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .payment-password-wrapper {
      flex-direction: column;
      margin: 20px;
    }

    .brand-section {
      padding: 40px 20px;
    }

    .form-section {
      padding: 40px 20px;
    }

    .brand-title {
      font-size: 24px;
    }

    .form-title {
      font-size: 24px;
    }

    .steps-indicator {
      flex-direction: row;
      justify-content: center;
      gap: 30px;
    }

    .step {
      flex-direction: column;
      gap: 8px;
    }

    .step-text {
      font-size: 12px;
    }

    .payment-digit-input {
      width: 40px;
      height: 40px;
      font-size: 16px;
    }

    .payment-input-wrapper {
      gap: 8px;
    }

    .button-group {
      flex-direction: column;
    }
  }

  @media (max-width: 480px) {
    .payment-password-content {
      padding: 20px 0;
    }

    .container {
      padding: 0 10px;
    }

    .brand-section,
    .form-section {
      padding: 30px 15px;
    }

    .payment-digit-input {
      width: 35px;
      height: 35px;
      font-size: 14px;
    }

    .payment-input-wrapper {
      gap: 6px;
    }
  }
</style>
